package mspbots.autotask.data.core.contracts;

import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.autotask.common.ResultMsg;
import mspbots.autotask.data.core.AbstractToolsUtil;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.time.Duration;

@Log4j2
@Component
@RequiredArgsConstructor
public class ContractBlocksReceiver extends AbstractToolsUtil {

    private final ContractBlocksRepository contractBlocksRepository;

    @RabbitListener(queues = "auto-task.contract-blocks.sync")
    public void syncTask(ResultMsg content) {

        ContractBlock contractBlock = ContractBlock.builder().otherId(content.getId())
                .tenantId(content.getTenantId())
                .syncTime(content.getSyncDate())
//                .createdTime(LocalDateTime.parse(content.getEntity().get("endDate").textValue(),
//                        DateTimeFormatter.ISO_OFFSET_DATE_TIME))
//                .updatedTime(LocalDateTime.parse(content.getEntity().get("datePurchased").textValue(),
//                        DateTimeFormatter.ISO_OFFSET_DATE_TIME))
                .entity(content.getEntity())
                .build();

        if (ObjectUtils.isEmpty(contractBlock.getOtherId())) {
            return;
        }

        this.contractBlocksRepository.findByOtherIdAndTenantId(content.getId(), content.getTenantId())
                .map(ticket -> {
                    contractBlock.setId(ticket.getId());
                    return contractBlock;
                })
                .defaultIfEmpty(contractBlock)
                .flatMap(this.contractBlocksRepository::save)
                .block(Duration.ofSeconds(10));
    }

}
